import { useDispatch, useSelector } from "react-redux"
import { IssueData } from "../../Types/Api/issue"
import style from "./index.module.css"
import { Tag } from "antd"
import { ROOT_STATE } from "../../store"
import { reqGetUserById } from "../../api/user"
import { useEffect, useState } from "react"
import { User } from "../../Types/Api/user"
import { reqAllType } from "../../api/tagType"
import { changeTypeList } from "../../store/typeSlice"
import { useNavigate } from "react-router-dom"
const tagColors = [
  "#FF5733",
  "#33FF57",
  "#5733FF",
  "#FF33D1",
  "#33D1FF",
  "#D1FF33",
  "#FFA533",
  "#33FFA5",
  "#A533FF",
  "#FF337F",
  "#337FFF",
  "#7FFF33",
]
type Props = {
  issueInfo: IssueData
}
export const IssueCard = ({ issueInfo }: Props) => {
  const typeList = useSelector(
    (state: ROOT_STATE) => state.typeReducer.typeList
  )
  const dispatch = useDispatch()
  const [user, setUser] = useState<User | undefined>()
  const getAllType = async () => {
    if (typeList.length === 0) {
      const { data } = await reqAllType()
      dispatch(changeTypeList(data))
    }
  }
  // typeid
  // [{typeid:xxx, typeName:react}]
  // reqGetUserById(issueInfo.userId)
  const getUserInfo = async () => {
    const { data } = await reqGetUserById(issueInfo.userId)
    setUser(data)
  }
  useEffect(() => {
    getUserInfo()
    getAllType()
  }, [])

  const findTypeName = (id: string) => {
    return typeList.find((item) => item._id === id)?.typeName
  }
  const findIndex = (id: string) => {
    return typeList.findIndex((item) => item._id === id)
  }
  const navigate = useNavigate()

  return (
    <div className={style.wrapper}>
      {/* 回答 */}
      <div className={style.num}>
        <div>{issueInfo.commentNumber}</div>
        <div>回答</div>
      </div>
      {/* 浏览 */}
      <div className={style.num}>
        <div>{issueInfo.scanNumber}</div>
        <div>浏览</div>
      </div>
      {/* 内容 */}
      <div className={style.content}>
        <div
          className={style.title}
          onClick={() => navigate("/issues/" + issueInfo._id)}
        >
          {issueInfo.issueTitle}
        </div>
        <div className={style.bottom}>
          <Tag
            style={{ marginRight: "auto" }}
            color={tagColors[findIndex(issueInfo.typeId)]}
          >
            {findTypeName(issueInfo.typeId)}
          </Tag>
          <Tag color="red">{user?.nickname}</Tag>
          <div>{new Date(+issueInfo.issueDate).toLocaleDateString()}</div>
        </div>
      </div>
    </div>
  )
}
